import type { AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'
import axios from 'axios'
import { ElMessage } from 'element-plus'

class requestMethods {
  instance: AxiosInstance
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config)
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        const res = response.data
        if (response.config.download) {
          return res
        }
        if (res.code !== 200) {
          ElMessage.error(res.msg)
          return Promise.reject(res)
        } else {
          return res
        }
      },
      (err: any) => {
        ElMessage.error(err.message)
        return Promise.reject(err)
      }
    )
    this.instance.interceptors.request.use(
      (config) => {
        return config
      },
      (err) => {
        ElMessage.error(err.message)
        return Promise.reject(err)
      }
    )
  }
  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.instance
        .request<any, T>(config)
        .then((res) => {
          resolve(res)
        })
        .catch((err: any) => {
          ElMessage.error(err.message)
          reject(err)
        })
    })
  }
  get<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'get' })
  }
  post<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: 'post' })
  }
}

const baseURL = '/api'
const axiosInstance = new requestMethods({
  baseURL,
  timeout: 10000
})

export default axiosInstance
